package cn.wind.xboot.module.web.controller.sys;

import cn.wind.xboot.core.annotation.RestJsonController;
import cn.wind.xboot.core.res.ApiResult;
import cn.wind.xboot.logic.sys.entity.SysLog;
import cn.wind.xboot.framework.domain.PageVo;
import cn.wind.xboot.framework.domain.SearchVo;
import cn.wind.xboot.framework.web.controller.BaseController;
import cn.wind.xboot.module.web.vo.sys.SysLogVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Arrays;
import java.util.stream.Collectors;


/**
 * 拥有ROLE_ADMIN角色的用户可以访问
 *
 * @author Exrickx
 */
@Slf4j
@RestJsonController
@Api(value = "log", tags = "日志管理接口")
@RequestMapping("log")
public class LogController extends BaseController<SysLog, Long> {



    @PreAuthorize("hasRole('system:log:view')")
    @GetMapping
    @ApiOperation(value = "分页搜索")
    public ApiResult get(SysLogVo sysLogVo,PageVo pageVo, SearchVo searchVo) {
        QueryWrapper<SysLog> ew = new QueryWrapper<>();
        if (sysLogVo.getSearchKey() != null) {
            ew.lambda().like(SysLog::getRequestUrl, sysLogVo.getSearchKey())
                    .or().like(SysLog::getRequestType, sysLogVo.getSearchKey())
                    .or().like(SysLog::getRequestParam, sysLogVo.getSearchKey())
                    .or().like(SysLog::getUsername, sysLogVo.getSearchKey())
                    .or().like(SysLog::getIp, sysLogVo.getSearchKey())
                    .or().like(SysLog::getIpInfo, sysLogVo.getSearchKey())
                    .or().like(SysLog::getName, sysLogVo.getSearchKey());
        }
        IPage<SysLog> log = sysLogService.page(pageVo.init(), ew);
        return ApiResult.Custom().success().add(log);
    }

    @PreAuthorize("hasRole('system:log:delete')")
    @DeleteMapping
    @ApiOperation(value = "批量删除")
    @Override
    public ApiResult delete(@RequestParam Long[] ids) {
        sysLogService.removeByIds(Arrays.stream(ids).collect(Collectors.toList()));
        return ApiResult.Custom().success("删除成功");
    }
    /**
     * 删除全部
     *
     * @return
     */
    @PreAuthorize("hasRole('system:log:delete')")
    @DeleteMapping("all")
    @ApiOperation(value = "全部删除")
    public ApiResult delAll() {
        sysLogService.remove(new QueryWrapper<SysLog>());
        return ApiResult.Custom().success("删除成功");
    }
}
